/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Veiculo.java
 *
 * Created on 10/10/2012, 21:40:00
 */

package projeto;

import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import projeto.classes.ModeloTipoVeiculo;
import projeto.classes.ModeloVeiculo;
import projeto.classes.TipoVeiculoAcessaDados;
import projeto.classes.Util.Util;
import projeto.classes.VeiculoAcessaDados;

/**
 *
 * @author Angela
 */
public class Veiculo extends javax.swing.JInternalFrame {

    private ModeloVeiculo v;
    private VeiculoAcessaDados vDao;
    private ArrayList<ModeloVeiculo> lista;
    private ArrayList<ModeloTipoVeiculo> listaTipo = new ArrayList<ModeloTipoVeiculo>();
    private br.com.fatecpg.mdi.MDI2 mdi;
    
    /** Creates new form Veiculo */
    public Veiculo() {
        initComponents();
    }
    
    public Veiculo(projeto.classes.ModeloUsuario user, br.com.fatecpg.mdi.MDI2 mdi) {
        initComponents();
        //é usado apenas como parte da chamada do frame Tipo_Veiculo
        //do metodo btnCadastarTipoActionPerformed
        this.mdi = mdi;
        
        //getUsuarioAdmin igual a 0 quer dizer que ele é um usuario normal
        if (user.getUsuarioAdmin() == 0) {
            btnExcluir.setVisible(false);
            btnCadastarTipo.setVisible(false);
        }
        
        if (btnExcluir.isVisible()) {
            btnExcluir.setEnabled(false);
            btnCadastarTipo.setEnabled(false);
        }
        btnAlterar.setEnabled(false);
        cmbPesquisa.setEnabled(false);
        mostrarCampos(false);
        
        v = new ModeloVeiculo();
        vDao = new VeiculoAcessaDados();
        
        //carrega o combo de tipo de veiculo
        carregarComboTipo();
    }
    
    private void mostrarCampos(boolean flag) {
        txtAno.setEnabled(flag);
        txtCor.setEnabled(flag);
        txtMarca.setEnabled(flag);
        cmbTipo.setEnabled(flag);
        cmbCombustivel.setEnabled(flag);
        cmbTerceirizado.setEnabled(flag);
    }
    
    private void limparCampos() {
        txtAno.setText("");
        txtCor.setText("");
        txtMarca.setText("");
        lblCodigo.setText("--");
        if (cmbTipo.getItemCount() > 0) {
            cmbTipo.setSelectedIndex(0);
        }
        cmbCombustivel.setSelectedIndex(0);
        cmbTerceirizado.setSelectedIndex(0);
    }
    
    private void carregarComboTipo() {
        TipoVeiculoAcessaDados dao = new TipoVeiculoAcessaDados();
        ModeloTipoVeiculo vTipo;
        
        try {
            if (listaTipo.size() > 0) {
                listaTipo.clear();
                listaTipo = dao.consultaTodos();
            } else {
                listaTipo = dao.consultaTodos();
            }
            
            if(cmbTipo.getItemCount() > 0) {
                cmbTipo.removeAllItems();
            }
            
            if (!listaTipo.isEmpty()) {
                for (int i = 0; i < listaTipo.size(); i++) {
                    vTipo = listaTipo.get(i);
                    cmbTipo.addItem(vTipo.getTipoVeiculo());
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao consultar tipo " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void alterarLabels() {
        lblMarca.setForeground(Color.black);
        lblCodigo.setForeground(Color.black);
        lblAno.setForeground(Color.black);
        lblCor.setForeground(Color.black);
    }
    
    private boolean validar(String marca, String ano, String cor) {
        boolean valido = true;

        if (marca.length() < 3 || marca.length() >= 20) {
            lblMarca.setForeground(Color.red);
            valido = false;
        }

        if (ano.length() > 4 || ano.length() < 2 || !Util.isNumber(ano) ) {
            lblAno.setForeground(Color.red);
            valido = false;
        }

        if (cor.length() < 2  || cor.length() >= 20) {
            lblCor.setForeground(Color.red);
            valido = false;
        }

        if (!valido) {
            JOptionPane.showMessageDialog(this, "Os campos com o nome em vermelho são inválidos.\nPor favor corrija.", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } 
        
        return valido;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnConsultar = new javax.swing.JToggleButton();
        jLabel1 = new javax.swing.JLabel();
        lblMarca = new javax.swing.JLabel();
        txtMarca = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        btnCadastarTipo = new javax.swing.JButton();
        lblAno = new javax.swing.JLabel();
        txtAno = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        lblCor = new javax.swing.JLabel();
        txtCor = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cmbTerceirizado = new javax.swing.JComboBox();
        cmbCombustivel = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        cmbOpcaoPesquisa = new javax.swing.JComboBox();
        txtConsulta = new javax.swing.JTextField();
        cmbPesquisa = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        btnConsultarTodos = new javax.swing.JToggleButton();

        setTitle("Entrega Gado - Veiculos");
        setPreferredSize(new java.awt.Dimension(546, 440));

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("VEÍCULO");

        lblMarca.setText("Marca:");

        jLabel3.setText("Tipo:");

        btnCadastarTipo.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        btnCadastarTipo.setText("Cadastrar");
        btnCadastarTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCadastarTipoActionPerformed(evt);
            }
        });

        lblAno.setText("Ano:");

        jLabel5.setText("Combustível:");

        lblCor.setText("Cor:");

        jLabel8.setText("Terceirizado:");

        cmbTerceirizado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Não", "Sim" }));

        cmbCombustivel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gasolina", "Alcool", "Gás", "Diesel" }));

        jLabel7.setText("Consultar por:");

        cmbOpcaoPesquisa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Marca", "Combustivel", "Ano" }));

        cmbPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbPesquisaActionPerformed(evt);
            }
        });

        jLabel9.setText("Código:");

        lblCodigo.setText("--");

        btnConsultarTodos.setText("Todos");
        btnConsultarTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarTodosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(113, Short.MAX_VALUE)
                .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(61, 61, 61)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(66, 66, 66)
                        .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(95, 95, 95))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(lblAno)
                            .addComponent(lblCor)
                            .addComponent(jLabel5)
                            .addComponent(lblMarca)
                            .addComponent(jLabel7)
                            .addComponent(jLabel9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmbOpcaoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(cmbPesquisa, 0, 198, Short.MAX_VALUE)
                                    .addComponent(txtConsulta))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnConsultar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnConsultarTodos, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbTerceirizado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cmbCombustivel, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCor, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnCadastarTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(lblCodigo)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(207, 207, 207)
                        .addComponent(jLabel1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConsultar)
                    .addComponent(jLabel7)
                    .addComponent(cmbOpcaoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConsultarTodos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(lblCodigo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCadastarTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(cmbTerceirizado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(cmbCombustivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAno)
                    .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCor)
                    .addComponent(txtCor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnSair)
                    .addComponent(btnAlterar))
                .addGap(18, 18, 18)
                .addComponent(btnExcluir)
                .addGap(14, 14, 14))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
         if (btnNovo.getText().equals("Novo")) {
            mostrarCampos(true);
            limparCampos();
            alterarLabels();
            btnNovo.setText("Salvar");
            btnAlterar.setEnabled(false);
            if (btnExcluir.isVisible()) {
                btnExcluir.setEnabled(false);
                btnCadastarTipo.setEnabled(true);
            }
        } else {
            //clicou no salvar
             if (validar(txtMarca.getText(), txtAno.getText(), txtCor.getText())) {
                v.setNomeMarca(txtMarca.getText());
                v.setAno(txtAno.getText());
                v.setCor(txtCor.getText());
                v.setTipoCombustivel(cmbCombustivel.getSelectedIndex());
                v.setTerceirizado(cmbTerceirizado.getSelectedIndex());
                ModeloTipoVeiculo tv = listaTipo.get(cmbTipo.getSelectedIndex()); 
                int idTipo = tv.getId();
                v.setTipoVeiculoId(idTipo);

                try {
                    if (!vDao.incluir(v)) {
                        JOptionPane.showMessageDialog(this, "Dados gravados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnNovo.setText("Novo");
                        btnAlterar.setEnabled(true);
                        int maxId = vDao.consultaMaxId();
                        lblCodigo.setText(Integer.toString(maxId));
                        mostrarCampos(false);
                        alterarLabels();
                        if (btnExcluir.isVisible()) {
                            btnExcluir.setEnabled(true);
                            btnCadastarTipo.setEnabled(false);
                        }
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
             }
         }
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (btnAlterar.getText().equals("Alterar")) {
            mostrarCampos(true);
            alterarLabels();
            btnAlterar.setText("Salvar");
            if (btnExcluir.isVisible()) {
                btnExcluir.setEnabled(false);
                btnCadastarTipo.setEnabled(true);
            }
        } else {
            if (validar(txtMarca.getText(), txtAno.getText(), txtCor.getText())) {
                v.setId(Integer.parseInt(lblCodigo.getText()));
                v.setNomeMarca(txtMarca.getText());
                v.setAno(txtAno.getText());
                v.setCor(txtCor.getText());
                v.setTipoCombustivel(cmbCombustivel.getSelectedIndex());
                v.setTerceirizado(cmbTerceirizado.getSelectedIndex());
                ModeloTipoVeiculo tv = listaTipo.get(cmbTipo.getSelectedIndex()); 
                int idTipo = tv.getId();
                v.setTipoVeiculoId(idTipo);

                try {
                    if (vDao.alterar(v) > 0) {
                        JOptionPane.showMessageDialog(this, "Dados alterados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnAlterar.setText("Alterar");
                        mostrarCampos(false);
                        alterarLabels();
                        if (btnExcluir.isVisible()) {
                            btnExcluir.setEnabled(true);
                            btnCadastarTipo.setEnabled(false);
                        }
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
       if (lblCodigo.getText().equals("--")) {
            JOptionPane.showMessageDialog(this, "Registro inválido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            lblCodigo.setForeground(Color.red);
        } else {
            try {
                int id = Integer.parseInt(lblCodigo.getText());

                if (vDao.deletar(id) == 1) {
                    JOptionPane.showMessageDialog(this, "Registro excluido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                    limparCampos();
                    mostrarCampos(false);
                    alterarLabels();
                    btnExcluir.setEnabled(false);
                    btnAlterar.setEnabled(false);
                    btnCadastarTipo.setEnabled(false);
                }

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao excluir " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        if (txtConsulta.getText().isEmpty()) {
           JOptionPane.showMessageDialog(this, "Informe um valor para consulta", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
       } else {
           //limpa o ArrayList
            if (lista != null) {
                lista.clear();
            }
           
           String filtro = "";
           if (cmbOpcaoPesquisa.getSelectedIndex() == 0) {
                //pesquisa por nome
                filtro = "nm_marca LIKE '" + txtConsulta.getText() + "%'";  
            }
            
            if (cmbOpcaoPesquisa.getSelectedIndex() == 1) {
                //pesquisa por combustivel
                filtro = "tp_combustivel LIKE '" + txtConsulta.getText() + "%'"; 
            }
            
            if (cmbOpcaoPesquisa.getSelectedIndex() == 2) {
                //pesquisa por cor
                filtro = "nm_cor LIKE '" + txtConsulta.getText() + "%'"; 
            }
        
           try {
            lista = vDao.consulta(filtro);
            
            if (lista.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Não foram localizados veiculos: " + txtConsulta.getText(), "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            }
            
            if (lista.size() > 0) {
                //limpa a lista
                if (cmbPesquisa.getItemCount() > 0) {                   
                   cmbPesquisa.removeAllItems();
                }
                cmbPesquisa.setEnabled(true);
                btnAlterar.setEnabled(true);
                btnNovo.setText("Novo");
                mostrarCampos(false);
                alterarLabels();
                if (btnExcluir.isVisible()) {
                    btnExcluir.setEnabled(true);
                    btnCadastarTipo.setEnabled(true);
                }
                //seleciona o 1º (ou o unico) item da lista
                ModeloVeiculo modeloV = lista.get(0);
                cmbPesquisa.addItem(modeloV.getNomeMarca());
                cmbPesquisa.setSelectedIndex(0);   
            }
            
            if (lista.size() > 1) {
                //apenas inclui os outros componentes na lista (se houver)
                for (int i = 1; i <= lista.size() - 1; i++) {
                    ModeloVeiculo modeloV = lista.get(i);
                    cmbPesquisa.addItem(modeloV.getNomeMarca());
                }
              }
           } catch (Exception ex) {
               JOptionPane.showMessageDialog(this, "Erro ao consultar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
           }
       }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void cmbPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbPesquisaActionPerformed
        if (evt.getSource().getClass().getSimpleName().equals("JComboBox")) {
            JComboBox cmb = (JComboBox)evt.getSource();
            int index = cmb.getSelectedIndex();
            if (index != -1) {
                ModeloVeiculo modeloV = lista.get(index);
                String id = Integer.toString(modeloV.getId());
                String marca = modeloV.getNomeMarca();
                int combustivel = modeloV.getTipoCombustivel();
                int terceirizado = modeloV.getTerceirizado();
                String cor = modeloV.getCor();
                String ano = modeloV.getAno();
                lblCodigo.setText(id);
                txtMarca.setText(marca);
                txtCor.setText(cor);
                txtAno.setText(ano);
                cmbCombustivel.setSelectedIndex(combustivel);
                cmbTerceirizado.setSelectedIndex(terceirizado);
                
                //logica para localizar o tipo
                ModeloTipoVeiculo tv;
                
                for (int i = 0; i < listaTipo.size(); i++) {
                    tv = listaTipo.get(i);
                    
                    if (tv.getId() == modeloV.getTipoVeiculoId()) {
                        cmbTipo.setSelectedIndex(i);
                        break;
                    }
                }
            }
        }
    }//GEN-LAST:event_cmbPesquisaActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnCadastarTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCadastarTipoActionPerformed
        if (btnCadastarTipo.getText().equals("Cadastrar")) {
            Tipo_Veiculo h = new Tipo_Veiculo();
            mdi.getDesktopPane().add(h);
            h.setVisible(true);
            h.setResizable(true);
            h.setMaximizable(true);
            h.setClosable(true);
            btnCadastarTipo.setText("Atualizar");
        } else {
            btnCadastarTipo.setText("Cadastrar");
            carregarComboTipo();
        }
    }//GEN-LAST:event_btnCadastarTipoActionPerformed

    private void btnConsultarTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarTodosActionPerformed
        Veiculo_ConsultaTodos vTodos = new Veiculo_ConsultaTodos(mdi, true);
        vTodos.setVisible(true);
    }//GEN-LAST:event_btnConsultarTodosActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnCadastarTipo;
    private javax.swing.JToggleButton btnConsultar;
    private javax.swing.JToggleButton btnConsultarTodos;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cmbCombustivel;
    private javax.swing.JComboBox cmbOpcaoPesquisa;
    private javax.swing.JComboBox cmbPesquisa;
    private javax.swing.JComboBox cmbTerceirizado;
    private javax.swing.JComboBox cmbTipo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel lblAno;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblCor;
    private javax.swing.JLabel lblMarca;
    private javax.swing.JTextField txtAno;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JTextField txtCor;
    private javax.swing.JTextField txtMarca;
    // End of variables declaration//GEN-END:variables

}
